package com.abe.libcore.base.http

import android.content.Context
import com.abe.libcore.base.http.converter.BaseConverterFactory
import com.abe.libcore.base.http.interceptor.MoreBaseUrlEntity
import com.abe.libcore.base.http.interceptor.MoreBaseUrlInterceptor
import com.google.gson.Gson
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory

object RetrofitUtils {
    /**
     * @param client 配置OkHttpClient
     * */
    fun getRetrofitBuilder(client: OkHttpClient): Retrofit.Builder {
        return Retrofit
                .Builder()
                .client(client)
    }

    fun getRetrofitBuilder(context: Context): Retrofit.Builder {
        return getRetrofitBuilder(OkHttpClientUtils.initHttpClient(context))
    }

    /**
     * @param moreBaseUrl 匹配多BaseUrl
     * */
    fun getRetrofitBuilder(context: Context, moreBaseUrl: Array<MoreBaseUrlEntity>, vararg interceptors: Interceptor): Retrofit.Builder {
        val moreBaseUrlInterceptor = MoreBaseUrlInterceptor(moreBaseUrl)
        val allInterceptor: Array<Interceptor> = arrayOf(*interceptors, moreBaseUrlInterceptor)
        val client = OkHttpClientUtils.initHttpClient(context, *allInterceptor)
        return getRetrofitBuilder(client)
    }

    fun getJsonRetrofit(client: OkHttpClient, gson: Gson): Retrofit.Builder {
        return getRetrofitBuilder(client).addConverterFactory(BaseConverterFactory.create(gson))
    }

    fun getJsonRetrofit(context: Context, gson: Gson): Retrofit.Builder {
        return getRetrofitBuilder(context).addConverterFactory(BaseConverterFactory.create(gson))
    }

    /**
     * @param moreBaseUrl 匹配多BaseUrl
     * */
    fun getJsonRetrofit(context: Context, moreBaseUrl: Array<MoreBaseUrlEntity>, gson: Gson): Retrofit.Builder {
        return getRetrofitBuilder(context, moreBaseUrl).addConverterFactory(BaseConverterFactory.create(gson))
    }
}